To count the number of words in a string, we split the string into words using whitespace as the delimiter and then count the number of resulting words.
def count_words(string):
return len(string.split())
def count_and_display_words():
string = input("Enter a string: ")
word_count = count_words(string)
print("Number of words in the string:", word_count)
# Example usage
count_and_display_words()
Enter a string: Hello world
Number of words in the string: 2
Enter a string: This is a sample sentence with more words
Number of words in the string: 8
The function count_words(string)
splits the input string using whitespace as the delimiter and returns the number of resulting words.
The function count_and_display_words()
takes input for a string, counts its words using the first function, and displays the count.